﻿using JT808Gateway.Core.Forwarders;
using JT808Gateway.Data;
using JT808Protocol.Abstracts;
using JT808Protocol.Handlers;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Quartz;
using Quartz.Impl;
using System;
using System.Text;

namespace JT808Gateway.Core.Extensions
{
    public static class JT808GatewayExtension
    {
        private static IHost _host = null;

        private static JT808GatewayOptions _options = null;

        public static void AddJT808Gateway(this IServiceCollection services, Action<JT808GatewayOptions> configure)
        {
            //注册编码
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            _options = new JT808GatewayOptions();
            configure(_options);

            MsgHandlerBase.AlarmAttachmentServerIP = _options.AttachmentServer.IP;
            MsgHandlerBase.AlarmAttachmentServerPort = _options.AttachmentServer.Port;

            var cacheService = new CacheService();
            //注入缓存
            services.AddSingleton(cacheService);
            //注入仓储
            services.AddSingleton<ForwardingServerRepository>();
            services.AddSingleton<ForwardingServerBindingRepository>();

            StartJob();

            var hostBuilder = new JT808GatewayHostBuilder()
                .SetCache(cacheService)
                .SetHost(_options.GatewayServer.Host)
                .SetPort(_options.GatewayServer.Port)
                .SetForwaders(forwarders =>
                {
                    //添加外部转发器
                    forwarders.AddRange(_options.Forwarders);
                    //内置转发器
                    forwarders.Add(new TcpForwarder());
                    forwarders.Add(new UdpForwarder());
                    forwarders.Add(new InMemoryForwarder(services));
                })
                .SetMeesageHandlers(msgHandlers =>
                {
                    //添加处理器
                    msgHandlers.AddRange(JT808HandlerProvider.GetHandlers());
                });
            _host = hostBuilder.Build();
        }

        public static async void UseJT808Gateway(this IApplicationBuilder app)
        {
            //启动网关
            await _host.RunAsync();
        }

        private static async void StartJob()
        {
            StdSchedulerFactory factory = new StdSchedulerFactory();
            IScheduler scheduler = await factory.GetScheduler();

            IJobDetail job = JobBuilder.Create<RefreshBindingsJob>()
                .WithIdentity("refreshbindingsjob", "group1")
                .Build();

            IJobDetail job2 = JobBuilder.Create<TcpReconnectJob>()
                .WithIdentity("tcpreconnectjob", "group1")
                .Build();

            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("refreshbindingsjob", "group1")
                .StartNow() //立即执行
                .WithSimpleSchedule(x => x.WithIntervalInMinutes(1).RepeatForever()) //每隔1分钟执行1次
                .Build();

            ITrigger trigger2 = TriggerBuilder.Create()
                .WithIdentity("tcpreconnectjob", "group1")
                .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever()) //每隔5秒钟执行1次
                .Build();

            await scheduler.ScheduleJob(job, trigger);
            await scheduler.ScheduleJob(job2, trigger2);

            await scheduler.Start();
        }
    }
}